package cl.parser.internal;

import java.util.ArrayList;
import java.util.List;

import cl.parser.IParseNode;
import cl.parser.external.CloseParenNode;
import cl.parser.external.CommaNode;
import cl.parser.external.OpenParenNode;

public class ArgumentsNode extends InternalNode implements IFat {

    @Override
    protected List<IParseNode> getAllowed(IParseNode last, List<IParseNode> soFar) {
        List<IParseNode> allowed = new ArrayList<IParseNode>();
        
        if(last == null) {
            allowed.add(new OpenParenNode());
        } else if(last instanceof OpenParenNode) {
            allowed.add(new ExpressionNode());
            allowed.add(new CloseParenNode());
        } else if(last instanceof ExpressionNode) {
            allowed.add(new CommaNode());
            allowed.add(new CloseParenNode());
        } else if(last instanceof CommaNode) {
            allowed.add(new ExpressionNode());
        } 
        
        return allowed;
    }

    @Override
    public String prettyPrint(String indent) {
        String res = "(";
        
        for(IParseNode p : children) {
            res += p.prettyPrint(indent) + ", ";
        }
        
        if(children.size() > 0) {
            res = res.substring(0, res.length() - 2);
        }
        
        return res + ")";
    }
    
    @Override
    public void loseWeight() {
        // remove ( )
        children.remove(0);
        children.remove(children.size() - 1);
        
        for(int i = 0;i < children.size(); i++) {
            if(children.get(i) instanceof CommaNode) {
                children.remove(i--);
            }
        }
    }

    @Override
    protected boolean isValid(IParseNode last, List<IParseNode> soFar) {
        return last instanceof CloseParenNode;
    }

}
